@echo off
chcp 65001>nul
::LayaAirIDE目录，根据自己的目录修改
set IDE_DIR=E:\Program Files\LayaAirIDE\

set IDE_APP_DIR=%IDE_DIR%resources\app\
set gulpjs=%IDE_APP_DIR%node_modules\gulp\bin\gulp.js
set compilejs=%~dp0..\.laya\compile.js

::创建一个js文件
echo let app = require("electron").app>compile_temp.js
echo let gulp = require('gulp')>>compile_temp.js
echo let childprocess = require('child_process')>>compile_temp.js
echo let defaultTask = "compile">>compile_temp.js
echo let gulpFile="%compilejs:\=\\%">>compile_temp.js
echo let gulpDir="%gulpjs:\=\\%">>compile_temp.js
echo let cmd = [`--gulpfile=${gulpFile}`, defaultTask]>>compile_temp.js
echo let fork1 = childprocess.fork(gulpDir, cmd,{silent: true})>>compile_temp.js
echo fork1.stdout.on("data", (data) =^> {>>compile_temp.js
echo let str = String(data)>>compile_temp.js
echo console.log(str)>>compile_temp.js
echo if(str.match(/^\s*Error\:/)){app.exit(1);return;}>>compile_temp.js
echo let isTasksComplete = str.match(/^laya\.ide\.complete$/m)>>compile_temp.js
echo if (isTasksComplete){>>compile_temp.js
echo app.exit(0)}>>compile_temp.js
echo })>>compile_temp.js
echo fork1.stderr.on("data", (err) =^> {let errStr=String(err);console.log(errStr);if(errStr.indexOf("Circular dependency")^<0){app.exit(1)}})>>compile_temp.js

::备份LayaAirIDE原有入口js文件
if not exist "%IDE_APP_DIR%out\main2.js" (
	copy "%IDE_APP_DIR%out\main.js" "%IDE_APP_DIR%out\main2.js" /y
)
::替换LayaAirIDE原有入口js文件
copy compile_temp.js "%IDE_APP_DIR%out\main.js" /y

::运行编译
"%IDE_DIR%LayaAir2.exe"
set compileErrCode=%errorlevel%

::还原LayaAirIDE原有入口js文件
copy "%IDE_APP_DIR%out\main2.js" "%IDE_APP_DIR%out\main.js" /y

if %compileErrCode%==0 (
	echo 编译完成
) else (
	echo 编译失败
	pause
	exit
)